import dva from 'dva';
import {voteDetail, saveVote, createVote, submitVote} from '../services/vote';
import {message} from 'antd';


export default {
  namespace: 'vote',
  state: {
    loading: true,
    error: '',
    submitLoading: false
  },
  reducers: {
    detail(state, {payload: {data: data}}) {
      return {...state, ...data.data, ...{loading: false}};
    },
    savevote(state, {payload: {data:data}}) {
      if (data.code == 201) {
        return {...state, ...data.data, ...{loading: false, error: ''}};
      } else {
        return {...state, ...{loading: false, error: data.data.error}};
      }
    },
    submitReducer(state, {payload: {data:data}}) {
      if (data.code == 201) {
        message.success('操作成功');
        return {...state, ...{loading: false, error: ''}};
      } else {
        message.error(data.data.error);
        return {...state, ...{error: data.data.error}};
      }
    },
    submitLoadingReducer(state, {payload: {loading: loading}}){
      return {...state, ...{submitLoading: loading}};
    }
  },
  effects: {
    *fetch({payload: {id}}, {call, put}) {
      const {data} = yield call(voteDetail, {id});
      yield put({type: 'detail', payload: {data: data}});
    },
    *create({payload: query}, {call, put}) {
      const {data} = yield call(createVote, query);
      yield put({type: 'savevote', payload: {data: data}});
    },
    *modify({payload: query}, {call, put}){
      const {data} = yield call(saveVote, query);
      yield put({type: 'savevote', payload: {data: data}});
    },
    *submit({payload: query}, {call, put}) {
      const {data} = yield call(submitVote, query);
      yield put({type: 'submitReducer', payload: {data: data}});
    }
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname, query}) => {
        if (pathname === '/vote' || pathname === '/votemodify') {
          dispatch({type: 'fetch', payload: query});
        }
      });
    }
  },
};
